import Notify from "../miniprogram_npm/@vant/weapp/notify/notify";

export enum Method {
    get = "GET",
    post = "POST",
    DELETE = "DELETE",
    put = "PUT"
}

// 开发环境
const { miniProgram: { envVersion } } = wx.getAccountInfoSync();

// 请求根
export const baseUrl = () => {
    switch (envVersion) {
        // http://192.168.31.8:3001/api/front
        // 开发
        case "develop":
            return "http://localhost:3001/api/front";
        // 体验
        case "trial":
            return "http://192.168.31.8:3001/api/front";
        // 发布
        case "release":
            return "http://192.168.31.8:3001/api/front";
    }
}

// 请求封装
const request = (method: Method, url: string, data?: any) => {
    return new Promise((resolve, reject) => {
        // 请求开始
        wx.request({
            url: baseUrl() + url,
            method,
            data,
            header: {
                'content-type': 'application/json'
            },
            success(res: any) {
                if (res.statusCode >= 400) return reject(res.data.data.msg);
                resolve(res.data.data.data);
            },
            fail(err: any) {
                Notify({ type: 'danger', message: err.data.data.msg });
                reject(err)
            }
        })
    })
}

export default request;